# -*- coding: utf-8 -*-
from config import rss_sources
from feed_parser import fetch_feed, get_article_text
from sentiment import score_sentiment, summarize_articles
from notification import notify_wechat
from utils import current_date_str, save_raw_articles

def main():
    daily_articles = []
    analysis_text = ""

    for category, feeds in rss_sources.items():
        for name, url in feeds.items():
            print(f"正在抓取: {name}")
            feed = fetch_feed(url)
            if not feed:
                continue
            for entry in feed.entries[:3]:
                title = entry.get('title', '无标题')
                link = entry.get('link', '')
                pub_time = entry.get('published', '无时间')

                content = get_article_text(link)
                sentiment = score_sentiment(content)

                article_data = {
                    "title": title,
                    "link": link,
                    "published": pub_time,
                    "content": content,
                    "source": name,
                    "sentiment_score": sentiment
                }

                daily_articles.append(article_data)
                analysis_text += f"【{title}】\n{content}\n\n"

    # 汇总摘要
    summary = summarize_articles(analysis_text)

    # 构造推送内容
    final_msg = f"📅 {current_date_str()} 财经新闻摘要\n\n"
    final_msg += f"🧠 要点概览：\n{summary}\n\n---\n"

    for item in daily_articles:
        final_msg += f"- [{item['title']}]({item['link']}) ｜ {item['source']} ｜ 情绪得分: {item['sentiment_score']}\n"

    # 推送
    notify_wechat(f"{current_date_str()} 财经资讯", final_msg)

    # 保存原文数据
    save_raw_articles(daily_articles)

if __name__ == "__main__":
    main()
